package ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;

/**
 * @author shenhan
 * @create 2020/2/10 16:29
 * @description
 */
public class FtpUtil {
    private static final Logger log = LoggerFactory.getLogger(FtpUtil.class);

    private void upload(String ip, int port, String userName, String passwd) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 1. 连接登录
            ftpClient.connect(ip, port);
            boolean loginSuccessful = ftpClient.login(userName, passwd);
            log.info(loginSuccessful ? "登录成功" : "登录失败");
            String remotePath = "/root/";
            String remotePathAfterTransferCode = new String(remotePath.getBytes("utf-8"), "iso-8859-1");
            String localFile = "C:\\Users\\shenhan\\Desktop\\development\\demo\\javaproxy\\pom.xml";
            String remoteFilename = "pom.xml";

            // 2. 在 ftp server 上创建文件夹
            boolean makeDirSuccessful = ftpClient.makeDirectory(remotePathAfterTransferCode);
            System.out.println("创建文件夹是否成功？ " + makeDirSuccessful);

            // 3. 切换目录
            boolean changeWorkingDirectorySuccessful = ftpClient.changeWorkingDirectory(remotePathAfterTransferCode);
            System.out.println(changeWorkingDirectorySuccessful ? "切换目录成功" : "切换目录失败");

            // 4. 上传本地文件到 ftp server
            boolean uploadSuccessful = ftpClient.storeFile(remoteFilename, new FileInputStream(new File(localFile)));
            System.out.println(uploadSuccessful ? "上传成功" : "上传失败");

            // 5. 退出登录
            ftpClient.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FtpUtil ftpUtil = new FtpUtil();
        ftpUtil.upload("192.168.129.128", 22, "root", "root");
    }
}
